package com.nexen.web.controller.system;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import com.nexen.system.domain.SysUserHisotry;
import com.nexen.system.service.ISysUserHisotryService;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.nexen.common.annotation.Log;
import com.nexen.common.config.RuoYiConfig;
import com.nexen.common.core.controller.BaseController;
import com.nexen.common.core.domain.AjaxResult;
import com.nexen.common.core.domain.entity.SysUser;
import com.nexen.common.core.domain.model.LoginUser;
import com.nexen.common.enums.BusinessType;
import com.nexen.common.utils.SecurityUtils;
import com.nexen.common.utils.StringUtils;
import com.nexen.common.utils.file.FileUploadUtils;
import com.nexen.common.utils.file.MimeTypeUtils;
import com.nexen.framework.web.service.TokenService;
import com.nexen.system.service.ISysUserService;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 个人信息 业务处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController
{
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysUserHisotryService userHisotryService;      // 用户密码修改记录表

    @Autowired
    private TokenService tokenService;
    @Autowired
    private FileStorageService fileStorageService;//注入实列

    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile()
    {
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return ajax;
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user)
    {
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getUser();
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhonenumber(user.getPhonenumber());
        currentUser.setSex(user.getSex());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser))
        {
            return error("修改用户'" + loginUser.getUsername() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser))
        {
            return error("修改用户'" + loginUser.getUsername() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(currentUser) > 0)
        {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        LoginUser loginUser = getLoginUser();
        SysUser nowUser = loginUser.getUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        SysUserHisotry userHisotry = null;

        // 正则表达式，匹配至少包含一个大写字母、一个小写字母、一个数字和一个特殊符号的字符串
        String REGEX_LENGTH = "^.{8,20}$";
        String REGEX = "^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[~!@#$%^&*]).{8,20}$";
        if (!Pattern.matches(REGEX_LENGTH, newPassword)) {
            return error("新密码长度在8到20之间");
        }
        if (!Pattern.matches(REGEX, newPassword))
        {
            return error("必须包含大小写字母、数字、特殊字符 ~ ! @ # $ % ^ & *");
        }

        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return error("新密码不能与旧密码相同");
        }

        // 改造密码记录
        userHisotry = new SysUserHisotry();
        userHisotry.setUserId(nowUser.getUserId());
        List<SysUserHisotry> sysUserHisotries = userHisotryService.selectSysUserHisotryList(userHisotry);
        if (ArrayUtil.isNotEmpty(sysUserHisotries) && sysUserHisotries.size() > 0) {
            for (int i = 0; i < sysUserHisotries.size(); i++) {
                SysUserHisotry userHisotryNew = sysUserHisotries.get(i);
                String uesrHistoryPwd = userHisotryNew.getPassword();
                if (SecurityUtils.matchesPassword(newPassword, uesrHistoryPwd)){
                    return error("新密码不能不同与前三次设置的密码相同");
                }
            }
        }

        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(userName, newPassword) > 0)
        {
            if(ObjUtil.isNotEmpty(userHisotry)) {
                userHisotry.setPassword(newPassword);
                userHisotry.setLoginIp(loginUser.getLoginLocation());
                userHisotry.setLoginDate(DateUtil.date(loginUser.getLoginTime()));
                // 插入用户密码修改记录
                userHisotryService.insertSysUserHisotry(userHisotry);
            }

            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
            // 去掉本地文件上传 TODO 2024-07-30
//            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            String filePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "/";
            FileInfo fileInfo = fileStorageService.of(file)
                    .setPath("avatar/" + filePath) //保存到相对路径下，为了方便管理，不需要可以不写//保存一些属性，可以在切面、保存上传记录、自定义存储平台等地方获取使用，不需要可以不写
                    .upload();  //将文件上传到对应地方

            String avatar = "";
            if (ObjUtil.isNotEmpty(fileInfo)) {
                avatar = fileInfo.getUrl();
            }
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }
}
